package com.wang.jmonkey.ca.api;

import com.wang.jmonkey.ca.service.SystemUserService;
import com.wang.jmonkey.common.constant.CacheConstant;
import com.wang.jmonkey.common.model.vo.UserVo;
import com.wang.jmonkey.common.result.HttpResult;
import com.wang.jmonkey.common.utils.UserUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.core.RedisOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.SessionCallback;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * @Description
 * @Author HeJiawang
 * @Date 2021/5/13 15:23
 */
@Slf4j
@RestController
@RequestMapping("/oauth")
public class OAuthApi {

    @Autowired
    private RedisTemplate<String , Object> redis;

    @Autowired
    private SystemUserService systemUserService;

    /**
     * 获取当前登录用户信息
     * @param request
     * @return
     */
    @GetMapping("userInfo")
    public HttpResult<UserVo> userInfo(HttpServletRequest request) {
        HttpResult<UserVo> result = new HttpResult<>();

        try {
            String userName = UserUtil.Info.getUsername(request);

            UserVo userVo = redis.execute(new SessionCallback<>(){

                @Override
                public UserVo execute(RedisOperations operations) throws DataAccessException {
                    if (operations.opsForHash().hasKey(CacheConstant.PermissionCache.USER_INFO.getKey(), userName)) {
                        return (UserVo) operations.opsForHash().get(CacheConstant.PermissionCache.USER_INFO.getKey(), userName);
                    }

                    UserVo userVo = systemUserService.selectUserVo(userName);
                    operations.opsForHash().put(CacheConstant.PermissionCache.USER_INFO.getKey(), userName, userVo);

                    return userVo;
                }
            });

            result.setData(userVo);
        }
        catch (Exception e) {

            log.error(this.getClass().getName() + "." + Thread.currentThread().getStackTrace()[1].getMethodName(), e);
            result.error(e.getMessage());
        }

        return result;
    }

}
